package com.yz.design.ThreadTask;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
 * @ClassName AThread
 * @Description TODO
 * @Author 广长
 * @Date 2020/6/16
 * @Version V1.0
 **/
public class MyCallableThreadTest {

    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName() + "主线程执行开始！");
        try {

            //创建线程池
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            // 创建一个callable子线程
            MyCallable myCallable = new MyCallable();
            // 把创建的callable子线程放到线程池，Future来获取结果
//            Future<Long> future = executorService.submit(myCallable);
            // 通过Future接口实现类获取结果，线程池执行
            FutureTask<Long> future = new FutureTask<>(myCallable);
            executorService.submit(future);


            // 关闭线程池
            executorService.shutdown();
//            Thread.sleep(2000);
            System.out.println(Thread.currentThread().getName() + "主线程在执行其他任务");

            // 获取子线程的值
            if (future.get() == null) {
                System.out.println("callable子线程未执行完！");
            } else {
                System.out.println("callable子线程执行结束，结果为：" + future.get());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "主线程执行结束！");

    }

}

class MyCallable implements Callable<Long> {

    @Override
    public Long call() throws Exception {
        long sum = 0;

        System.out.println(Thread.currentThread().getName() + "子线程执行开始");
        for (int i = 0; i < 10000000; i++) {
            sum = sum + i;
        }
        System.out.println(Thread.currentThread().getName() + "子线程执行结束");
        return sum;
    }
}



